<template>
  <div class="edit-profile">
    <van-nav-bar
      title="修改个人信息"
      left-arrow
      @click-left="router.back()"
    />

    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <!-- 姓名 -->
        <van-field
          v-model="formData.name"
          name="name"
          label="姓名"
          placeholder="请输入姓名"
          :rules="[{ required: true, message: '请输入姓名' }]"
        />

        <!-- 性别 -->
        <van-field
          v-model="formData.genderText"
          name="gender"
          label="性别"
          readonly
        />

        <!-- 手机号码 -->
        <van-field
          v-model="formData.phone"
          name="phone"
          label="手机号码"
          placeholder="请输入手机号码"
          :rules="[
            { required: true, message: '请输入手机号码' },
            { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' }
          ]"
        />

        <!-- 身份证号 -->
        <van-field
          v-model="formData.idCard"
          name="idCard"
          label="身份证号"
          placeholder="请输入身份证号"
          :rules="[
            { pattern: /^\d{17}[\dXx]$/, message: '请输入正确的身份证号' }
          ]"
        />

        <!-- 地址 -->
        <van-field
          v-model="formData.address"
          name="address"
          label="地址"
          type="textarea"
          rows="2"
          placeholder="请输入地址"
        />

        <!-- 邮箱 -->
        <van-field
          v-model="formData.email"
          name="email"
          label="邮箱"
          placeholder="请输入邮箱"
          :rules="[
            { pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, message: '请输入正确的邮箱格式' }
          ]"
        />
      </van-cell-group>

      <!-- 紧急联系人部分 -->
      <div class="section">
        <div class="section-header">
          <span class="section-title">紧急联系人</span>
        </div>
        <van-cell-group inset>
          <!-- 已有的紧急联系人列表 -->
          <template v-if="formData.emergencyContacts?.length">
            <van-swipe-cell v-for="contact in formData.emergencyContacts" :key="contact.id">
              <van-cell center :title="contact.name" :label="contact.relationship">
                <template #value>
                  <div class="contact-phone">{{ contact.phone }}</div>
                </template>
              </van-cell>
              <template #right>
                <van-button 
                  square 
                  type="danger" 
                  text="删除" 
                  class="delete-btn"
                  @click="handleDeleteContact(contact.id)"
                />
              </template>
            </van-swipe-cell>
          </template>
          
          <!-- 添加新的紧急联系人 -->
          <van-field
            v-model="formData.emergencyContact"
            name="emergencyContact"
            label="联系人姓名"
            placeholder="请输入紧急联系人姓名"
          />
          <van-field
            v-model="formData.emergencyPhone"
            name="emergencyPhone"
            label="联系人电话"
            placeholder="请输入紧急联系人电话"
            :rules="[
              { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' }
            ]"
          />
          <div class="add-contact-btn">
            <van-button 
              type="primary" 
              size="small" 
              icon="plus"
              @click="handleAddContact"
            >
              添加联系人
            </van-button>
          </div>
        </van-cell-group>
      </div>

      <!-- 提交按钮 -->
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit">
          保存修改
        </van-button>
      </div>
    </van-form>

    <!-- 性别选择器 -->
    <van-popup v-model="showGenderPicker" position="bottom">
      <van-picker
        :columns="genderOptions"
        @confirm="onGenderConfirm"
        @cancel="showGenderPicker = false"
        show-toolbar
        title="选择性别"
      />
    </van-popup>

    <!-- 日期选择器 -->
    <van-calendar
      v-model="showDatePicker"
      @confirm="onDateConfirm"
      :min-date="minDate"
      :max-date="maxDate"
      title="选择出生日期"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showSuccessToast, showFailToast } from 'vant'
import { getUserProfile, updateUserProfile } from '../api'

const router = useRouter()

// 表单数据
const formData = reactive({
  id: null,
  createTime: '',
  deleted: 0,
  username: '',
  password: '',
  name: '',
  phone: '',
  email: '',
  gender: '',
  genderText: '',
  avatar: '',
  role: 1,
  status: 1,
  consultationFee: 0,
  birthDate: '',
  address: '',
  emergencyContact: '',
  emergencyPhone: '',
  idCard: '',
  emergencyContacts: []  // 添加紧急联系人数组
})

// 选择器相关
const showGenderPicker = ref(false)
const showDatePicker = ref(false)

const genderOptions = ['男', '女']

// 日期限制
const minDate = new Date(1900, 0, 1)
const maxDate = new Date()

// 获取用户信息
const loadUserInfo = async () => {
  try {
    const res = await getUserProfile()
    if (res.code === 200) {
      const userInfo = res.data
      // 保存所有字段
      Object.assign(formData, {
        ...userInfo,
        emergencyContacts: userInfo.emergencyContacts || []  // 确保有默认值
      })
      // 特殊处理性别显示
      formData.genderText = userInfo.gender === 1 ? '男' : '女'
    }
  } catch (error) {
    showFailToast('获取用户信息失败')
  }
}

// 添加紧急联系人
const handleAddContact = () => {
  if (!formData.emergencyContacts) {
    formData.emergencyContacts = []
  }
  formData.emergencyContacts.push({
    id: Date.now(),
    name: formData.emergencyContact,
    phone: formData.emergencyPhone,
    relationship: '亲属'  // 默认关系
  })
  // 清空输入
  formData.emergencyContact = ''
  formData.emergencyPhone = ''
}

// 删除紧急联系人
const handleDeleteContact = (contactId) => {
  formData.emergencyContacts = formData.emergencyContacts.filter(
    contact => contact.id !== contactId
  )
}

// 初始化数据
onMounted(() => {
  loadUserInfo()
})

// 性别选择确认
const onGenderConfirm = (value) => {
  formData.genderText = value
  formData.gender = value === '男' ? 1 : 2
  showGenderPicker.value = false
}

// 日期选择确认
const onDateConfirm = (value) => {
  formData.birthDate = value.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  }).replace(/\//g, '-')
  showDatePicker.value = false
}

// 提交表单
const onSubmit = async () => {
  try {
    // 提交时保留所有原有字段
    const data = {
      ...formData,
      gender: formData.gender,  // 确保使用数字类型的性别值
    }
    
    const res = await updateUserProfile(data)
    if (res.code === 200) {
      showSuccessToast('保存成功')
      router.back()
    } else {
      showFailToast(res.message || '保存失败')
    }
  } catch (error) {
    showFailToast('保存失败')
  }
}
</script>

<style scoped>
.edit-profile {
  min-height: 100vh;
  background-color: #f7f8fa;
}

.section {
  margin-top: 12px;
}

.section-header {
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #323233;
}

.add-contact-btn {
  padding: 12px 16px;
  display: flex;
  justify-content: center;
}

:deep(.van-cell-group) {
  margin: 12px 0;
}

.delete-btn {
  height: 100%;
  width: 65px;
}

.contact-phone {
  font-size: 14px;
  color: #969799;
}
</style> 